Imports System
Imports System.Data.SqlClient
Imports Wrox.Commerce


Partial Class Checkout
    Inherits System.Web.UI.Page

    Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Trace.Write("In Page_Load")

        If Not Page.IsPostBack Then
            If Profile.Cart Is Nothing Then
                NoCartlabel.Visible = True
                Wizard1.Visible = False
            End If

            Trace.Write("In Page_Load", User.Identity.IsAuthenticated.ToString())
            If User.Identity.IsAuthenticated Then
                Wizard1.ActiveStepIndex = 1
            Else
                Wizard1.ActiveStepIndex = 0
            End If
        End If

    End Sub

    Sub chkUseProfileAddress_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        ' fill the delivery address from the profile, but only if it's empty
        ' we don't want to overwrite the values
        If chkUseProfileAddress.Checked AndAlso txtName.Text.Trim() = "" Then
            txtName.Text = Profile.Name
            txtAddress.Text = Profile.Address
            txtCity.Text = Profile.City
            txtCounty.Text = Profile.County
            txtPostCode.Text = Profile.PostCode
            txtCountry.Text = Profile.Country
        End If

    End Sub

    Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs)

        ' Insert the order and order lines into the database
        Dim conn As SqlConnection = Nothing
        Dim trans As SqlTransaction = Nothing
        Dim cmd As SqlCommand


        Try
            conn = New SqlConnection(ConfigurationManager.ConnectionStrings("WroxUnited").ConnectionString)
            conn.Open()

            trans = conn.BeginTransaction

            cmd = New SqlCommand()
            cmd.Connection = conn
            cmd.Transaction = trans

            ' set the order details
            cmd.CommandText = "INSERT INTO Orders(MemberName, OrderDate, Name, Address, County, PostCode, Country, SubTotal, Discount, Total) " & _
                             "VALUES (@MemberName, @OrderDate, @Name, @Address, @County, @PostCode, @Country, @SubTotal, @Discount, @Total)"
            cmd.Parameters.Add("@MemberName", Data.SqlDbType.VarChar, 50)
            cmd.Parameters.Add("@OrderDate", Data.SqlDbType.DateTime)
            cmd.Parameters.Add("@Name", Data.SqlDbType.VarChar, 50)
            cmd.Parameters.Add("@Address", Data.SqlDbType.VarChar, 255)
            cmd.Parameters.Add("@County", Data.SqlDbType.VarChar, 50)
            cmd.Parameters.Add("@PostCode", Data.SqlDbType.VarChar, 15)
            cmd.Parameters.Add("@Country", Data.SqlDbType.VarChar, 50)
            cmd.Parameters.Add("@SubTotal", Data.SqlDbType.Money)
            cmd.Parameters.Add("@Discount", Data.SqlDbType.Money)
            cmd.Parameters.Add("@Total", Data.SqlDbType.Money)

            cmd.Parameters("@MemberName").Value = User.Identity.Name
            cmd.Parameters("@OrderDate").Value = DateTime.Now()
            cmd.Parameters("@Name").Value = CType(Wizard1.FindControl("txtName"), TextBox).Text
            cmd.Parameters("@Address").Value = CType(Wizard1.FindControl("txtAddress"), TextBox).Text
            cmd.Parameters("@County").Value = CType(Wizard1.FindControl("txtCounty"), TextBox).Text
            cmd.Parameters("@PostCode").Value = CType(Wizard1.FindControl("txtPostCode"), TextBox).Text
            cmd.Parameters("@Country").Value = CType(Wizard1.FindControl("txtCountry"), TextBox).Text
            cmd.Parameters("@SubTotal").Value = Profile.Cart.SubTotal
            cmd.Parameters("@Discount").Value = Profile.Cart.MemberDiscount
            cmd.Parameters("@Total").Value = Profile.Cart.Total

            Dim OrderID As Integer
            OrderID = Convert.ToInt32(cmd.ExecuteScalar())


            ' change the query and parameters for the order lines
            cmd.CommandText = "INSERT INTO OrderLines(OrderID, ProductID, Quantity, Price) " & _
                             "VALUES (@OrderID, @ProductID, @Quantity, @Price)"
            cmd.Parameters.Clear()
            cmd.Parameters.Add("@OrderID", Data.SqlDbType.Int)
            cmd.Parameters.Add("@ProductID", Data.SqlDbType.Int)
            cmd.Parameters.Add("@Quantity", Data.SqlDbType.Int)
            cmd.Parameters.Add("@Price", Data.SqlDbType.Money)

            cmd.Parameters("@OrderID").Value = OrderID
            For Each item As CartItem In Profile.Cart.Items
                cmd.Parameters("@ProductID").Value = item.ProductID
                cmd.Parameters("@Quantity").Value = item.Quantity
                cmd.Parameters("@Price").Value = item.Price

                cmd.ExecuteNonQuery()
            Next

            ' commit the transaction
            trans.Commit()

        Catch SqlEx As SqlException
            ' some form of error - rollback the transaction 
            ' and rethrow the exception
            If trans IsNot Nothing Then
                trans.Rollback()
            End If

            ' Log the exception
            'Tools.log("An error occurred while creating the order", SqlEx)
            Throw New Exception("An error occurred while creating the order", SqlEx)

            CreateOrderErrorLabel.Visible = True

            Return
        Finally
            If conn IsNot Nothing Then
                conn.Close()
            End If

        End Try

        ' we will only reach here if the order has been created sucessfully
        ' so clear the cart
        Profile.Cart.Items.Clear()

    End Sub

    Sub Wizard1_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs)

        Trace.Write("next: CurrentStep", e.CurrentStepIndex.ToString())

        If e.CurrentStepIndex = 0 Then

            Dim l As System.Web.UI.WebControls.Login = CType(Wizard1.FindControl("Login1"), Login)

            If Membership.ValidateUser(l.UserName, l.Password) Then
                FormsAuthentication.SetAuthCookie(l.UserName, l.RememberMeSet)

                e.Cancel = False
            Else
                Trace.Write(l.UserName, l.Password)
                l.InstructionText = "Your login attempt was not successful. Please try again."
                l.InstructionTextStyle.ForeColor = System.Drawing.Color.Red

                e.Cancel = True
            End If
        Else
            If Not User.Identity.IsAuthenticated Then
                e.Cancel = True
                Wizard1.ActiveStepIndex = 0
            End If
        End If

    End Sub

    Protected Sub Wizard1_ActiveStepChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Wizard1.ActiveStepChanged

        If Not User.Identity.IsAuthenticated Then
            Trace.Write("step changed", "not authenticated, returning to step 0")
            Wizard1.ActiveStepIndex = 0
        End If

    End Sub

End Class
